﻿using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

internal class ApiExceptionFilter : IExceptionFilter
{
    private readonly ILogger _logger;
    public ApiExceptionFilter(ILogger<ApiExceptionFilter> logger)
    {
        _logger = logger;
    }

    public void OnException(ExceptionContext context)
    {
        if (context.Exception is ApiException ex)
            context.Result = new JsonResult(ex.ToApiExceptionResponse());
        else if (context.ActionDescriptor is ControllerActionDescriptor)
        {
            _logger.LogError(context.Exception.ToString());
            context.Result = new JsonResult(new ResponseError(EResponseCode.其他错误, context.Exception.Message + context.Exception.InnerException?.Message));
        }
        else
            _logger.LogError(context.Exception.ToString());

    }
}

public class ApiException : Exception
{
    public EResponseCode ErrorCode { get; set; }
    public string? ErrorMessage { get; set; }
    public ApiException() { }
    public ApiException(EResponseCode code, string? message = null)
    {
        ErrorCode = code;
        ErrorMessage = message;
    }
    public ResponseError ToApiExceptionResponse() => new ResponseError(ErrorCode, ErrorMessage);

}

public class ResponseError
{
    public EResponseCode Code { get; set; }
    public string? Message { get; set; }
    public ResponseError() { }
    public ResponseError(EResponseCode code, string? message)
    {
        Code = code;
        Message = message;
    }
}
public enum EResponseCode
{
    其他错误 = 1,
    订单不存在,
    订单号不能为空,
    已经有人入住,
    房价码错误,
    房型代码错误,
    房量不足,
    非空房,
    无空房,
    无需拆分,
    并发错误,
    证件信息不存在,
    GuestId不存在
}